"use client"

import {
    Card,
    CardHeader,
    Image,
    CardBody,
    Divider,
    Avatar,
    CardFooter,
    RadioGroup,
    Radio,
    cn,
    Progress
} from "@nextui-org/react"
import PropTypes from "prop-types";
import {Record, Topic} from "@/util/type";
import {useEffect, useState} from "react";
import {useAuth} from "@clerk/nextjs";

export default function TicketTopics({topic, getTopicById}: {
    topic: Topic,
    getTopicById: (id: string) => void
}) {
    const [selectOption, setSelectOption] = useState("")
    const {userId} = useAuth()
    const [isSelect, setIsSelect] = useState(false)
    const [count, setCount] = useState(0)

    // 获取用户对当前话题的投票记录
    const getRecord = async () => {
        const record = await fetch(`${process.env.API_ADDRESS}/record?topicId=${topic.id}&userId=${userId}`)
        const data = (await record.json()).record as Record
        if (record.status === 400) {
            setIsSelect(false)
        } else {
            setIsSelect(true)
            const totalValue = topic.options?.reduce((value, option) => {
                return value + option.value
            }, 0)
            setCount(totalValue)
            setSelectOption(data.chooseValue)
        }
    }
    useEffect(() => {
        getRecord()
    }, [])

    // 选中的选项发生变化
    const handleValueChange = async (changeValue: string) => {
        try {
            setSelectOption(changeValue)
            // 添加一条投票记录
            const response = await fetch(`${process.env.API_ADDRESS}/record`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    topicId: topic.id,
                    userId: userId,
                    chooseValue: changeValue
                })
            })
            const res = await response.json()
            // 通知父组件重新获取当前的话题数据
            await getTopicById(res.record.topicId)
            getRecord()
        } catch (e) {
            console.log("投票失败")
        }
    }

    return (
        <>
            <div className="w-10/12">
                <Card className="py-4">
                    <CardHeader className="pb-0 pt-2 px-4 flex-col items-start">
                        <Avatar src={topic.avatar} size="lg"/>
                        <h1 className="text-xl font-bold py-1 break-all">{topic.userId}</h1>
                        <p className="font-bold text-base break-all">{topic.content}</p>
                    </CardHeader>
                    <CardBody className="overflow-visible py-2">
                        <div className="flex flex-wrap">
                            {
                                topic.images?.split(",").map((src, index) => {
                                    return (
                                        <Image
                                            key={index}
                                            alt={topic.content}
                                            className="object-cover rounded-xl p-2"
                                            src={src}
                                            loading="lazy"
                                        />
                                    )
                                })
                            }
                        </div>
                    </CardBody>
                    <CardFooter>
                        <div className="flex flex-col justify-center items-center w-full">
                            <RadioGroup orientation="horizontal"
                                        value={selectOption}
                                        onValueChange={handleValueChange}>
                                {
                                    topic.options?.map(option => {
                                        return <Radio
                                            key={option.id}
                                            value={option.key}
                                            className={cn(
                                                "inline-flex m-0 bg-content1 hover:bg-content2 items-center justify-between",
                                                "flex-row-reverse max-w-[300px] cursor-pointer rounded-lg gap-4 p-4 border-2 border-transparent",
                                                "data-[selected=true]:border-primary",
                                            )}
                                        >{option.key}</Radio>
                                    })
                                }
                            </RadioGroup>
                            {
                                isSelect && topic.options?.map(option => {
                                    return (
                                        <div className="mt-2 w-11/12" key={option.id}>
                                        <Progress value={count === 0 ? 0 : option.value / count * 100}
                                                  label={option.key + `：${option.value}票`}
                                                  size="md"
                                                  radius="sm"
                                                  color="primary"
                                                  classNames={{
                                                      base: "w-full",
                                                      track: "drop-shadow-md border border-default",
                                                      label: "tracking-wider font-medium text-default-600",
                                                  }}
                                                  showValueLabel={true}
                                        />
                                        </div>)
                                })
                            }
                        </div>
                    </CardFooter>
                </Card>
            </div>
            <Divider className="my-5"/>
        </>

    )
}

PropTypes.array